﻿using System;
using System.DirectoryServices;

namespace CInChat.Security
{
    /// <summary>
    /// LDAP authentication helper
    /// </summary>
    public class LdapLogin
    {
        /// <summary>
        /// Domain address.
        /// </summary>
        private const string LDAP_URL = "LDAP://172.17.33.26/cn=Users,DC=windows,DC=cin,DC=ufpe,DC=br";

        /// <summary>
        /// Check if the user is valid for a given login.
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool IsValidUser(String domain, String username, String password) {
            try {
                String domainAndUsername = domain + @"\" + username;
                DirectoryEntry entry = new DirectoryEntry(LDAP_URL, domainAndUsername, password);
                DirectorySearcher searcher = new DirectorySearcher(entry, "(|(objectCategory=user)(cn=" + username + "))");
                var result = searcher.FindOne();
                return result != null;
            } catch {
                return false;
            }
        }
    }
}
